<template>
  <el-drawer v-model="dialogStatus" :close-on-click-modal="false" size="50%"
             @close="dialogOfClosedMethods(false)">
    <template #header>
      <h4>{{ title }}</h4>
    </template>
    <template #default>
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item :label="$t('merchant.name')" prop="merchantName">
              <el-input v-model="form.merchantName" :placeholder="$t('merchant.namePlaceholder')" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('merchant.code')" prop="merchantCode">
              <el-input v-model="form.merchantCode" :placeholder="$t('merchant.codePlaceholder')" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="父级商户" prop="parentCode">
              <el-select v-model="form.parentCode" clearable placeholder="请选择父级商户" style="width: 100%">
                <el-option
                  v-for="item in merchantOptions"
                  :key="item.id"
                  :label="item.merchantName"
                  :value="item.merchantCode">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('merchant.contact')" prop="contact">
              <el-input v-model="form.contact" :placeholder="$t('merchant.contactPlaceholder')" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item :label="$t('merchant.phone')" prop="phone">
              <el-input v-model="form.phone" :placeholder="$t('merchant.phonePlaceholder')" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('merchant.channel')" prop="channelCode">
              <el-select v-model="form.channelCode" :placeholder="$t('merchant.channelPlaceholder')" clearable style="width: 100%">
                <el-option
                  v-for="item in channelOptions"
                  :key="item.id"
                  :label="item.channelName"
                  :value="item.channelCode">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item :label="$t('merchant.address')" prop="address">
          <el-input v-model="form.address" type="textarea" :placeholder="$t('merchant.addressPlaceholder')" />
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item :label="$t('merchant.sortIndex')" prop="sortIndex">
              <el-input-number v-model="form.sortIndex" controls-position="right" :min="0" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('merchant.status')">
              <el-radio-group v-model="form.status">
                <el-radio
                    v-for="dict in sys_normal_disable"
                    :key="dict.value"
                    :label="dict.value"
                >{{ dict.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </template>
    <template #footer>
      <div style="flex: auto">
        <el-button @click="dialogOfClosedMethods(false)">{{ $t('jbx.text.close') }}</el-button>
        <el-button type="primary" @click="submitForm">{{ $t('jbx.text.submit') }}</el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script setup lang="ts">
import { ElForm } from 'element-plus'
import { reactive, ref, toRefs, watch, onMounted } from 'vue'
import { useI18n } from 'vue-i18n'
import modal from '@/plugins/modal'
import { getMerchant, saveMerchant, updateMerchant, listMerchant } from '@/api/merchant/merchant'
import { listChannel } from '@/api/channel/channel'

const { t } = useI18n()
const { proxy } = getCurrentInstance()!
const emit = defineEmits(['dialogOfClosedMethods'])
const dialogStatus = ref(false)
const formRef = ref<InstanceType<typeof ElForm> | null>(null)

// 字典数据
const { sys_normal_disable } = proxy.useDict("sys_normal_disable");

// 商户选项列表
const merchantOptions = ref([])

// 渠道选项列表
const channelOptions = ref([])

interface FormModel {
  id?: string
  parentCode?: string
  merchantName: string
  merchantCode: string
  contact: string
  phone: string
  channelCode: string
  address: string
  sortIndex: number
  status: number
}

interface FormState {
  form: FormModel
  rules: Record<string, any>
}

const props = defineProps<{
  title?: string
  open?: boolean
  formId?: string
}>()

const data = reactive<FormState>({
  form: {
    parentCode: undefined,
    merchantName: '',
    merchantCode: '',
    contact: '',
    phone: '',
    channelCode: '',
    address: '',
    sortIndex: 0,
    status: 1
  },
  rules: {
    merchantName: [{ required: true, message: t('merchant.nameRequired'), trigger: "blur" }],
    merchantCode: [{ required: true, message: t('merchant.codeRequired'), trigger: "blur" }],
    contact: [{ required: true, message: t('merchant.contactRequired'), trigger: "blur" }],
    phone: [{ required: true, message: t('merchant.phoneRequired'), trigger: "blur" }],
    sortIndex: [{ required: true, message: t('merchant.sortRequired'), trigger: "blur" }]
  }
})

const { form, rules } = toRefs(data)

// 获取商户列表
const getMerchantList = () => {
  listMerchant({}).then((response: any) => {
    if (response.code === "0") {
      merchantOptions.value = response.data.records
    }
  })
}

// 获取渠道列表
const getChannelList = () => {
  listChannel({}).then((response: any) => {
    if (response.code === "0") {
      channelOptions.value = response.data.records
    }
  })
}

onMounted(() => {
  getMerchantList()
  getChannelList()
})

watch(
    () => props.open,
    (val) => {
      if (val) {
        dialogStatus.value = val
        if (props.formId) {
          getMerchant(props.formId).then((res: any) => {
            form.value = res.data
          })
        } else {
          reset()
        }
      } else {
        dialogStatus.value = false
      }
    },
    { immediate: true }
)

// 重置表单
function reset() {
  form.value = {
    parentCode: undefined,
    merchantName: '',
    merchantCode: '',
    contact: '',
    phone: '',
    channelCode: '',
    address: '',
    sortIndex: 0,
    status: 1
  }
  formRef.value?.resetFields()
}

function dialogOfClosedMethods(val: any) {
  dialogStatus.value = false
  emit('dialogOfClosedMethods', val)
}

function submitForm() {
  formRef.value?.validate((valid: boolean) => {
    if (valid) {
      if (form.value.id) {
        updateMerchant(form.value).then((response: any) => {
          modal.msgSuccess(response.msg)
          dialogOfClosedMethods(true)
        })
      } else {
        saveMerchant(form.value).then((response: any) => {
          modal.msgSuccess(response.msg)
          dialogOfClosedMethods(true)
        })
      }
    }
  })
}
</script>